package com.afb

class UserController {
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    static allowedMethods = [delete:'POST', save:'POST', update:'POST']



        def teste = {
            render(view:'/user/teste')
//            render(view:'/user/login');
        }


	def entry = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)

		//        [ userInstanceList: User.list( params ), userInstanceTotal: User.count() ]
		//		render(view:'/user/login', model:[ userInstanceList: User.list( params ), userInstanceTotal: User.count() ]);
		//[ userInstanceList: User.list( params ), userInstanceTotal: User.count() ]


		//book = Book.findByReleaseDateGreaterThan( someDate )
		//
		//book = Book.findByTitleLikeOrReleaseDateLessThan( "%Something%", someDate )


		//		def month = params.month;
		//		if (!month) month =


		Calendar cal=Calendar.getInstance();
		int month = cal.get(Calendar.MONTH);


		def now = new Date()
		def nextLimit = now + 31
		//		def reserv = Reservation.findAllByDateBetween( now, nextLimit )
		//		def reserv = Reservation.findAllByUser7hOrUser8hOrUser9hOrUser10hOrUser11hOrUser12hOrUser13hOrUser14hOrUser15hOrUser16hOrUser17hOrUser18hOrUser19h(session?.user,session?.user,session?.user,session?.user,session?.user,session?.user,session?.user,session?.user,session?.user,session?.user,session?.user,session?.user,session?.user);
		//		def reserv = Reservation.findAllByUser7hLike(session?.user);  // funca
		//		def reserv = Reservation.findAllByUser7hOrUser8h(session?.user, session?.user);  // funca
//		def reserv = Reservation.findAllByUser7hOrUser8hOrUser9h(session?.user, session?.user, session?.user);
		//		def reserv = Reservation.findAllByUser7hOrUser8hOrUser9h(session?.user,session?.user,session?.user);

//		def criteria = Reservation.createCriteria()




		def model
//		role(inList:["Registered", "Supplier", "Director", "Administrator"])

		if (session?.user.role.equals("Administrator")) {

//			def listEquipAvariados = Equipament.findAllByOperationalLike("false");
//
			params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
//
//			def repairQuoteRequestInstanceList =  RepairQuoteRequest.list( params )
//			def repairQuoteRequestInstanceList =  RepairQuoteRequest.list()

//			render repairQuoteRequestInstanceList.size()


//			def repairQuoteRequestInstanceList = RepairQuoteRequest.list(params);
//			def repairQuoteRequestInstanceList = RepairQuoteRequest.findAll()

//			render repairQuoteRequestInstanceList.count();

			model = [
				userInstanceList: User.list( params ), userInstanceTotal: User.count(),
                                HHPredJobInstanceList: HHPredJob.findAllByUser(session?.user), HHPredJobInstanceTotal: HHPredJob.findByUser(session?.user)?.count()<=0?0:10,
//				reservationInstanceList: Reservation.list(params), reservationInstanceTotal: Reservation.count(),
//				reservationInstanceList: reserv, reservationInstanceTotal: reserv.count(),
//				malfunctionInstanceList: listEquipAvariados, malfunctionInstanceTotal: listEquipAvariados.count(),
//				repairQuoteRequestInstanceList:repairQuoteRequestInstanceList, repairQuoteRequestInstanceTotal:repairQuoteRequestInstanceList.count()
				]
		} else if (session?.user.role.equals("Registered")) {
//			render(reserv.count())

			model = [
				userInstanceList: User.list( params ), userInstanceTotal: User.count(),
// TODO
                                HHPredJobInstanceList: HHPredJob.findByUser(session?.user), HHPredJobInstanceTotal: HHPredJob.findByUser(session?.user)?.count()<=0?0:10,
//				reservationInstanceList: Reservation.list(params), reservationInstanceTotal: Reservation.count(),
//				reservationInstanceList: reserv, reservationInstanceTotal: reserv.count(),
//				malfunctionInstanceList: listEquipAvariados, malfunctionInstanceTotal: listEquipAvariados.count(),
//				repairQuoteRequestInstanceList:repairQuoteRequestInstanceList, repairQuoteRequestInstanceTotal:repairQuoteRequestInstanceList.count()
				]

		}


		return model


	}

	def authenticate = {
		def user = User.findByLoginAndPassword(params.login, params.password)
		if(user){
			session.user = user
			flash.message = "Hello ${user.name}!"

			//			if (params.cName) {
			//				redirect(controller:params.cName, action:params.aName)
			//			} else {
			redirect(action:"entry")
			//			}
		}else{
			flash.message = "Sorry, ${params.login}. Please try again."
			redirect(action:"login")
		}
	}


    def login = {
		if (session.user) redirect(action:entry)
		//			render(view:'/user/entry');

		if (params.cName) return [cName:params.cName, aName:params.aName]


		//		if (params.login == "admin" && params.password == "pass") {
		//			//			render "login succeed";
		//			flash.message = "login succeed";
		//			//			session.user = "admin";
		//			session.user = User.get(1);
		//		} else {
		//			flash.message = "login failed";
		//		}
		//		redirect(action: 'list');
    }

    def logout = {
		session.user = null;
                session._grails_console_last_code_= null;
		render(view:'/user/login');
    }


    def list = {
        params.max = Math.min( params.max ? params.max.toInteger() : 10,  100)
        [ userInstanceList: User.list( params ), userInstanceTotal: User.count() ]
    }

    def show = {
        def userInstance = User.get( params.id )

        if(!userInstance) {
            flash.message = "User not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ userInstance : userInstance ] }
    }

    def delete = {
        def userInstance = User.get( params.id )
        if(userInstance) {
            try {
                userInstance.delete()
                flash.message = "User ${params.id} deleted"
                redirect(action:list)
            }
            catch(org.springframework.dao.DataIntegrityViolationException e) {
                flash.message = "User ${params.id} could not be deleted"
                redirect(action:show,id:params.id)
            }
        }
        else {
            flash.message = "User not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def userInstance = User.get( params.id )

        if(!userInstance) {
            flash.message = "User not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ userInstance : userInstance ]
        }
    }

    def update = {
        def userInstance = User.get( params.id )
        if(userInstance) {
            if(params.version) {
                def version = params.version.toLong()
                if(userInstance.version > version) {
                    
                    userInstance.errors.rejectValue("version", "user.optimistic.locking.failure", "Another user has updated this User while you were editing.")
                    render(view:'edit',model:[userInstance:userInstance])
                    return
                }
            }
            userInstance.properties = params
            if(!userInstance.hasErrors() && userInstance.save()) {
                flash.message = "User ${params.id} updated"
                redirect(action:show,id:userInstance.id)
            }
            else {
                render(view:'edit',model:[userInstance:userInstance])
            }
        }
        else {
            flash.message = "User not found with id ${params.id}"
            redirect(action:edit,id:params.id)
        }
    }

    def create = {
        def userInstance = new User()
        userInstance.properties = params
        return ['userInstance':userInstance]
    }

    def save = {
        def userInstance = new User(params)
        if(!userInstance.hasErrors() && userInstance.save()) {
            flash.message = "User ${userInstance.id} created"
            redirect(action:show,id:userInstance.id)
        }
        else {
            render(view:'create',model:[userInstance:userInstance])
        }
    }


}
